/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;

namespace Xceed.Silverlight.Data
{
  public abstract class IndexDataSourceProvider : DataSourceProvider
  {
    #region Constructor

    internal IndexDataSourceProvider()
      : base()
    {
    }

    #endregion

    #region CanCount Property

    public sealed override bool CanCount
    {
      get
      {
        return true;
      }
    }

    #endregion

    #region CanGroupCount Property

    public override bool CanGroupCount
    {
      get
      {
        return false;
      }
    }

    #endregion

    #region CanSkip Property

    public sealed override bool CanSkip
    {
      get
      {
        return true;
      }
    }

    #endregion

    #region CanFilter Property

    public sealed override bool CanFilter
    {
      get
      {
        return false;
      }
    }

    #endregion

    #region CanJumpToItem Property

    public sealed override bool CanJumpToItem
    {
      get
      {
        return true;
      }
    }

    #endregion

    #region CanJump Property

    public sealed override bool CanJump
    {
      get
      {
        return this.CanFind;
      }
    }

    #endregion

    #region CanFilterGroup Property

    public override bool CanFilterGroup
    {
      get
      {
        return false;
      }
    }

    #endregion

    #region CanFind Property

    public virtual bool CanFind
    {
      get
      {
        return false;
      }
    }

    #endregion

    #region CanSort Internal Property

    internal sealed override bool CanSort
    {
      get
      {
        return true;
      }
    }

    #endregion

    #region CanFilterPredicate Internal Property

    internal sealed override bool CanFilterPredicate
    {
      get
      {
        return false;
      }
    }

    #endregion

    #region CanJumpToDeletedItem Internal Property

    internal sealed override bool CanJumpToDeletedItem
    {
      get
      {
        return true;
      }
    }

    #endregion

    #region IsPrimaryKeyVolatile Internal Property

    internal sealed override bool IsPrimaryKeyVolatile
    {
      get
      {
        return true;
      }
    }

    #endregion

    protected override void Initialize()
    {
      if( this.CanGroupCount )
      {
        if( !this.CanFind )
          throw new DataInternalException();
      }

      m_indexHelper = new IndexHelper( this, Enumerable.Empty<SortDescription>() );

      base.Initialize();
    }

    protected sealed override IEnumerable<SortDescription> GetPrimaryKeyInfo()
    {
      yield return new SortDescription( IndexDataItem.IndexKeyName, ListSortDirection.Ascending );
    }

    protected sealed override IEnumerable<FilterOperator> GetSupportedFilterOperators( Type dataType )
    {
      return Enumerable.Empty<FilterOperator>();
    }

    internal sealed override bool IsSortOrderSupported( IEnumerable<SortDescription> sortOrder )
    {
      // We must exclude the index key name from the sorted properties since it is
      // unknown for a custom data source.
      List<SortDescription> newSortOrder = ( from sd in sortOrder
                                             where sd.PropertyName != IndexDataItem.IndexKeyName
                                             select sd ).ToList();

      if( newSortOrder.Count == 0 )
        return true;

      return base.IsSortOrderSupported( newSortOrder );
    }

    internal sealed override bool CanJumpTo( IEnumerable<SortDescription> properties )
    {
      return this.CanJump;
    }

    internal sealed override bool FindElementMemberType( string memberName, out Type type )
    {
      if( memberName == IndexDataItem.IndexKeyName )
      {
        type = typeof( IndexKey );
        return true;
      }

      return base.FindElementMemberType( memberName, out type );
    }

    internal sealed override IAsyncResult BeginExecuteCountQueryCore(
      CountQueryParameters queryParameters,
      AsyncCallback callback,
      object state )
    {
      return m_indexHelper.BeginGetItemsCount( queryParameters, callback, state );
    }

    internal sealed override CountQueryResult EndExecuteCountQueryCore( IAsyncResult asyncResult )
    {
      return m_indexHelper.EndGetItemsCount( asyncResult );
    }

    internal sealed override IAsyncResult BeginExecuteDataQueryCore(
      DataQueryParameters queryParameters,
      AsyncCallback callback,
      object state )
    {
      return m_indexHelper.BeginGetItems( queryParameters, callback, state );
    }

    internal sealed override DataQueryResult EndExecuteDataQueryCore( IAsyncResult asyncResult )
    {
      DataQueryResult queryResult = m_indexHelper.EndGetItems( asyncResult );

      List<IndexDataItem> dataItems = new List<IndexDataItem>();
      foreach( IndexDataObject item in queryResult.Data.Cast<IndexDataObject>() )
      {
        RawDataItem dataItem = item.DataObject as RawDataItem;
        if( dataItem == null )
        {
          dataItem = new RawDataItem( item.DataObject );
        }

        IndexKey key = new IndexKey( this, item.Context, item.Index );
        IndexDataItem newDataItem = new IndexDataItem( dataItem, key );

        dataItems.Add( newDataItem );
      }

      return new DataQueryResult(
               dataItems,
               queryResult.InlineCount,
               queryResult.TotalCount );
    }

    internal sealed override IAsyncResult BeginExecuteGroupCountQueryCore(
      GroupCountQueryParameters queryParameters,
      AsyncCallback callback,
      object state )
    {
      return m_indexHelper.BeginGetGroupCount( queryParameters, callback, state );
    }

    internal sealed override GroupCountQueryResult EndExecuteGroupCountQueryCore( IAsyncResult asyncResult )
    {
      return m_indexHelper.EndGetGroupCount( asyncResult );
    }

    internal sealed override IAsyncResult BeginExecuteStatQueryCore(
      StatQueryParameters queryParameters,
      AsyncCallback callback,
      object state )
    {
      return m_indexHelper.BeginGetStatValue( queryParameters, callback, state );
    }

    internal sealed override StatQueryResult EndExecuteStatQueryCore( IAsyncResult asyncResult )
    {
      return m_indexHelper.EndGetStatValue( asyncResult );
    }

    internal abstract IAsyncResult BeginExecuteCountQueryIndexed(
      CountQueryParameters queryParameters,
      AsyncCallback callback,
      object state );

    internal abstract CountQueryResult EndExecuteCountQueryIndexed( IAsyncResult asyncResult );

    internal abstract IAsyncResult BeginExecuteDataQueryIndexed(
      DataQueryParameters queryParameters,
      AsyncCallback callback,
      object state );

    internal abstract DataQueryResult EndExecuteDataQueryIndexed( IAsyncResult asyncResult );

    internal abstract IAsyncResult BeginExecuteFindQueryIndexed(
      FindQueryParameters queryParameters,
      AsyncCallback callback,
      object state );

    internal abstract FindQueryResult EndExecuteFindQueryIndexed( IAsyncResult asyncResult );

    internal abstract IAsyncResult BeginExecuteGroupCountQueryIndexed(
      GroupCountQueryParameters queryParameters,
      AsyncCallback callback,
      object state );

    internal abstract GroupCountQueryResult EndExecuteGroupCountQueryIndexed( IAsyncResult asyncResult );

    internal abstract IAsyncResult BeginExecuteStatQueryIndexed(
      StatQueryParameters queryParameters,
      AsyncCallback callback,
      object state );

    internal abstract StatQueryResult EndExecuteStatQueryIndexed( IAsyncResult asyncResult );

    internal sealed override bool TryWrapDataObject( object item, out RawDataItem dataItem )
    {
      IndexDataItem localDataItem = item as IndexDataItem;
      object childItem = ( localDataItem != null )
                           ? localDataItem.ChildDataItem
                           : item;

      // Make sure the child item is of the appropriate type.
      if( !base.TryWrapDataObject( childItem, out dataItem ) )
        return false;

      if( ( localDataItem == null ) || ( !object.Equals( childItem, dataItem ) ) )
      {
        IndexKey primaryKey = new IndexKey( this, DataQueryContext.None );
        localDataItem = new IndexDataItem( dataItem, primaryKey );
      }

      dataItem = localDataItem;

      return true;
    }

    internal sealed override bool TryUnwrapDataObject( RawDataItem dataItem, out object item )
    {
      IndexDataItem localDataItem = dataItem as IndexDataItem;
      if( localDataItem != null )
        return base.TryUnwrapDataObject( localDataItem.ChildDataItem, out item );

      item = null;
      return false;
    }

    internal sealed override bool TryUnwrapLayer( RawDataItem dataItem, out object item )
    {
      item = dataItem;

      return ( dataItem != null );
    }

    #region Private Fields

    private IndexHelper m_indexHelper;

    #endregion

    #region Private IndexHelper Nested Type

    private class IndexHelper : IndexDataSourceProviderHelper
    {
      internal IndexHelper(
        IndexDataSourceProvider dataSourceProvider,
        IEnumerable<SortDescription> defaultSortOrder )
        : base( defaultSortOrder )
      {
        if( dataSourceProvider == null )
          throw new ArgumentNullException( "dataSourceProvider" );

        m_dataSourceProvider = dataSourceProvider;
      }

      protected override bool CanFind
      {
        get
        {
          return m_dataSourceProvider.CanFind;
        }
      }

      protected override bool CanSortBy( IEnumerable<SortDescription> sortOrder )
      {
        return m_dataSourceProvider.IsSortOrderSupported( sortOrder );
      }

      protected override IAsyncResult BeginCountQuery(
        CountQueryParameters queryParameters,
        AsyncCallback callback,
        object state )
      {
        Debug.Assert( ( queryParameters.Filter == null )
                   && ( queryParameters.Jump == null ) );
        Debug.Assert( ( queryParameters.FilterGroup == null && queryParameters.Sort == null )
                   || ( queryParameters.FilterGroup != null && queryParameters.Sort != null && m_dataSourceProvider.CanFilterGroup ) );

        return m_dataSourceProvider.BeginExecuteCountQueryIndexed( queryParameters, callback, state );
      }

      protected override CountQueryResult EndCountQuery( IAsyncResult asyncResult )
      {
        return m_dataSourceProvider.EndExecuteCountQueryIndexed( asyncResult );
      }

      protected override IAsyncResult BeginDataQuery(
        DataQueryParameters queryParameters,
        AsyncCallback callback,
        object state )
      {
        Debug.Assert( ( queryParameters.Filter == null )
                   && ( queryParameters.ItemJump == null )
                   && ( queryParameters.Jump == null ) );

        return m_dataSourceProvider.BeginExecuteDataQueryIndexed( queryParameters, callback, state );
      }

      protected override DataQueryResult EndDataQuery( IAsyncResult asyncResult )
      {
        return m_dataSourceProvider.EndExecuteDataQueryIndexed( asyncResult );
      }

      protected override IAsyncResult BeginFindQuery(
        FindQueryParameters queryParameters,
        AsyncCallback callback,
        object state )
      {
        Debug.Assert( ( queryParameters.Filter == null )
                   && ( queryParameters.Sort != null )
                   && ( queryParameters.Find != null ) );

        return m_dataSourceProvider.BeginExecuteFindQueryIndexed( queryParameters, callback, state );
      }

      protected override FindQueryResult EndFindQuery( IAsyncResult asyncResult )
      {
        return m_dataSourceProvider.EndExecuteFindQueryIndexed( asyncResult );
      }

      protected override IAsyncResult BeginGroupCountQuery( 
        GroupCountQueryParameters queryParameters, 
        AsyncCallback callback, 
        object state )
      {
        Debug.Assert( ( queryParameters.Sort != null )
                   && ( queryParameters.Take != null ) );

        return m_dataSourceProvider.BeginExecuteGroupCountQueryIndexed( queryParameters, callback, state );
      }

      protected override GroupCountQueryResult EndGroupCountQuery( IAsyncResult asyncResult )
      {
        return m_dataSourceProvider.EndExecuteGroupCountQueryIndexed( asyncResult );
      }

      protected override IAsyncResult BeginStatQuery(
        StatQueryParameters queryParameters,
        AsyncCallback callback,
        object state )
      {
        Debug.Assert( ( queryParameters.Filter == null )
                   && ( queryParameters.Function != null ) );
        Debug.Assert( ( queryParameters.FilterGroup == null && queryParameters.Sort == null )
                   || ( queryParameters.FilterGroup != null && queryParameters.Sort != null && m_dataSourceProvider.CanFilterGroup ) );

        return m_dataSourceProvider.BeginExecuteStatQueryIndexed( queryParameters, callback, state );
      }

      protected override StatQueryResult EndStatQuery( IAsyncResult asyncResult )
      {
        return m_dataSourceProvider.EndExecuteStatQueryIndexed( asyncResult );
      }

      private IndexDataSourceProvider m_dataSourceProvider;
    }

    #endregion
  }
}
